package org.chaiyi.template.core.framework.support;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.chaiyi.template.core.common.repository.BuDefaultSetting;
import org.chaiyi.template.core.common.supporter.Supporter;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Gong.Yang
 */
@Component
@RequiredArgsConstructor
public class DefaultSupportManager {
    private final ConcurrentHashMap<String, Mono<BuDefaultSetting>> buDefaultMap = new ConcurrentHashMap<>();

    private final ReactiveMongoOperations baseMongo;

    public <T extends Supporter> Mono<T> get(String tenantId, String buCode, Class<T> ownerClass) {
        return buDefaultMap.computeIfAbsent(getKey(tenantId, buCode), key -> {
            Query query = Query.query(
                    Criteria.where("tenantId").is(tenantId).and("buCode").is(buCode));
            return baseMongo.findOne(query, BuDefaultSetting.class);
        }).map(x -> BeanUtil.copyProperties(x, ownerClass));
    }

    private String getKey(String tenantId, String buCode) {
        return tenantId + "_" + buCode;
    }
}
